<?php
/**
 * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures
 * all the essential functionalities required for any enterprise.
 * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com
 *
 * OrangeHRM is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * OrangeHRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA
 *
 */
require_once ROOT_PATH . '/lib/confs/Conf.php';
require_once ROOT_PATH . '/lib/confs/sysConf.php';
require_once ROOT_PATH . '/lib/models/time/Timesheet.php';
require_once ROOT_PATH . '/lib/models/time/TimeEvent.php';
require_once ROOT_PATH . '/lib/models/time/ProjectReport.php';
require_once ROOT_PATH . '/lib/common/TemplateMerger.php';

require_once ROOT_PATH . '/lib/models/time/AttendanceRecord.php';
require_once ROOT_PATH . '/lib/controllers/AttendanceController.php';
require_once ROOT_PATH . '/lib/extractor/time/EXTRACTOR_AttendanceRecord.php';

/**
 *统计员工各种考勤类 
 **/
class AttendanceStatistics extends AttendanceController {



	var $AttendanceCache;
	var $db = "";


	public function __construct() {
		include(ROOT_PATH . '/customConfig/attendance.config.php');
		$this->AttendanceCache = $_CfgAttendance;
		$this->db = new DMLFunctions();
		error_reporting(0);
	}

	public function __distruct() {
		$this->db->dbDisconnect();
	}
	
	/**
	 *统计员工请假次数 
	 * $type:特殊考勤类型
	 * $dayType:统计日期类型 0：月 1：季度 2:年度
	 * $dayTime 如果是月 array(2012,01)  如果是季度 array(2012,2) 如果是年  2012
	 **/
	public function StatisticsSpAttendance($EmpId='',$type=1,$dayType=0,$dayTime="") {
		$result = $this->GetJiJieTime($dayType,$dayTime);
		$StartTime = $result['StartTime'];
		$EndTime = $result['EndTime'];
		//echo @date("Y-m-d H:i:s",$StartTime)."<br>";
		//echo @date("Y-m-d H:i:s",$EndTime)."<br>";
		if($EmpId != "") {
			$where = " and EmpId = {$EmpId} ";
		}
		//查出所有符合这段时间内的特殊考勤的记录
		$sql = "select * from hs_hr_emp_attendance_sp where TypeId in ({$type}) {$where} and ((StartTime >= {$StartTime} and StartTime < {$EndTime}) or (EndTime > {$StartTime} and EndTime <= {$EndTime}) or (StartTime < {$StartTime} and EndTime > {$EndTime}))";
		//echo $sql;
		//die();
		$query = $this->db->executeQuery($sql);
		$num = 0;
		$time = 0;
		//计算出这段时间的周末有多少天，节假日有多少天
		$WeekAndHolidays = $this->GetWeekAndHolidays();
		$WeekDay = $this->GetWeekHavaDay($StartTime,$EndTime,$WeekAndHolidays['Week'][0]);
		$Holidays = $this->GetHolidayHavaDay($StartTime,$EndTime,$WeekAndHolidays['Holidays']);
		$EmpInfo = array();
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			//首先判断是当前时间之前请假，不过在本时间内结束
			if($row['StartTime'] < $StartTime && $row['EndTime'] <= $EndTime) {
				$EmpInfo[$row['EmpId']][$row['TypeId']]['time'] += $row['EndTime'] - $StartTime;
			} elseif($row['StartTime'] >= $StartTime && $row['EndTime'] <= $EndTime) {//判断是当前时间内请假，在本时间内结束
				$EmpInfo[$row['EmpId']][$row['TypeId']]['time'] += $row['EndTime'] - $row['StartTime'];
			} elseif($row['StartTime'] >= $StartTime && $row['EndTime'] > $EndTime) {//判断是当前时间内请假，在本时间外结束
				$EmpInfo[$row['EmpId']][$row['TypeId']]['time'] += $EndTime - $row['StartTime'];
			} elseif($row['StartTime'] < $StartTime && $row['EndTime'] > $EndTime) {//判断是当前时间前请假，在本时间外结束
				$EmpInfo[$row['EmpId']][$row['TypeId']]['time'] += $EndTime - $StartTime;
			}
			$EmpInfo[$row['EmpId']][$row['TypeId']]['hour'] += $row['hour'];
			$EmpInfo[$row['EmpId']][$row['TypeId']]['num'] ++;
		}
		return array('TimeInfo'=>$EmpInfo,'WeekDay'=>$WeekDay,'Holidays'=>$Holidays);
	}
	
	/**
	 *计算出季度，月度，年度的开始时间和结束时间 
	 **/
	public function GetJiJieTime($dayType = 0,$dayTime="") {
		$MonJidu = array(1=>array(1,3),2=>array(4,6),3=>array(7,9),4=>array(10,12));
		if($dayType == 0) {
			//计算月
			if($dayTime == "") {
				$StartTime = mktime(0, 0, 0, @date("m"), 1, @date("Y"));
				$EndTime = mktime(0, 0, 0, @date("m")+1, 1, @date("Y"));
			} else {
				$StartTime = mktime(0, 0, 0, $dayTime[1], 1, $dayTime[0]);
				$EndTime = mktime(0, 0, 0, $dayTime[1]+1, 1, $dayTime[0]);
			}
		}elseif($dayType == 1) {
			//计算季度
			if($dayTime == "") {
				//得出本月是第几季度
				$Month = @date("m");
				$jidu = "";
				foreach ($MonJidu as $key => $val) {
					if($val[0] <= $Month) {
						$jidu = $key;
					}
				}
				$StartTime = mktime(0, 0, 0, $MonJidu[$jidu][0], 1, @date("Y"));
				$EndTime = mktime(0, 0, 0, $MonJidu[$jidu][1]+1, 1, @date("Y"));
			} else {
				$StartTime = mktime(0, 0, 0, $MonJidu[$dayTime[1]][0], 1, $dayTime[0]);
				$EndTime = mktime(0, 0, 0, $MonJidu[$dayTime[1]][1]+1, 1, $dayTime[0]);
			}
		} else {
			//计算年度
			if($dayTime == "") {
				$StartTime = mktime(0, 0, 0, 1, 1, @date("Y"));
				$EndTime = mktime(0, 0, 0, 1, 1, @date("Y")+1);
			} else {
				$StartTime = mktime(0, 0, 0, 1, 1, $dayTime);
				$EndTime = mktime(0, 0, 0, 1, 1, $dayTime+1);
			}
		}
		return array('StartTime'=>$StartTime,'EndTime'=>$EndTime);
	}
	
	
	/**
	 *计算两段时间内周末有多少天 
	 **/
	public function GetWeekHavaDay($StartTime,$EndTime,$WeekArr) {
		$WeekDayStart = @date('N',$StartTime); 
		$WeekDayEnd = @date('N',$EndTime); 
		$day = 0;
		$AllNum = 0;
		$NumWeek = intval(($EndTime - $StartTime)/(3600*24)) / 7;

		foreach ($WeekArr as $key => $val) {
			$AllNum += $val['num'];
		}
		if(($NumWeek < 1 && $WeekDayStart > $WeekDayEnd) || ($NumWeek == 1 && $WeekDayStart <= $WeekDayEnd)) { //判断首尾两日跨了两周
			for($i=$WeekDayStart; $i<=7;$i++) {
				if(isset($WeekArr[$i])) $day += $WeekArr[$i]['num'];
			}
			for($i=1; $i<=$WeekDayEnd;$i++) {
				if(isset($WeekArr[$i])) $day += $WeekArr[$i]['num'];
			}
		} elseif($NumWeek < 1 && $WeekDayStart < $WeekDayEnd) { //判断首尾只是在一周内
			for($i=$WeekDayStart; $i<=$WeekDayEnd;$i++) {
				if(isset($WeekArr[$i])) $day += $WeekArr[$i]['num'];
			}
		} elseif($NumWeek >= 1) {   //判断首尾两日中间隔离一周或者以上的
			//判断首尾两日不在相邻周
			$day += ((floor(($EndTime - $StartTime - (8-$WeekDayStart)*(3600*24) - ($WeekDayEnd-1)*3600*24) / (3600*24)))/7) * $AllNum ;
			for($i=$WeekDayStart; $i<=7;$i++) {
				if(isset($WeekArr[$i])) $day += $WeekArr[$i]['num'];
			}
			for($i=1; $i<$WeekDayEnd;$i++) {
				if(isset($WeekArr[$i])) $day += $WeekArr[$i]['num'];
			}
		}
		return $day;
	}
	
	/**
	 *计算两段时间内节假日有多少天 
	 **/
	public function GetHolidayHavaDay($StartTime,$EndTime,$HolidayArr) {
		if($HolidayArr=="") return 0;
		$day = 0;
		foreach ($HolidayArr as $key => $val) {
			if($val['recurring'] == 1) {
				$Sstr = @date("md",$StartTime);
				$Estr = @date("md",$EndTime);
				$Dstr = @date("md",strtotime($val['date']));
				if(($Sstr < $Dstr && $Estr > $Dstr) || ($Sstr > $Estr && ($Sstr < $Dstr || $Estr > $Dstr)) || ($Sstr <= $Estr && (@date("Y",$StartTime) != @date("Y",$EndTime)))) {
					$day += $val['num'];
				}
			} elseif($StartTime <= strtotime($val['date']) && $EndTime >= strtotime($val['date'])) {
				$day += $val['num'];
			}
		}
		return $day;
	}
	
	
	/**
	 *查询周末和节假日 
	 **/
	public function GetWeekAndHolidays() {
		$sql = "select * from `hs_hr_weekends` where `length` in (8,4)";
		$query = $this->db->executeQuery($sql);
		$day = 0;
		while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
			if($row['length'] == 8) { 
				$row['num'] = 1;
				$day += 1;
			}
			if($row['length'] == 4) {
				$row['num'] = 0.5;
				$day += 0.5;
			}
			$Week[$row['day']] = $row;
		}
		$sql = "select * from `hs_hr_holidays`";
		$query2 = $this->db->executeQuery($sql);
		while ($row2 = mysql_fetch_array($query2,MYSQL_ASSOC)) {
			if($row2['length'] == 8) $row2['num'] = 1;
			if($row2['length'] == 4) $row2['num'] = 0.5;
			$Holidays[] = $row2;
		}
		return array('Week'=>array($Week,$day),'Holidays'=>$Holidays);
	}
	
	
	/**
	 *统计员工迟到，早退 
	 **/
	public function StatisticsLaterTui($dayType=0,$dayTime="") {
		//获取开始和结束时间
		$result = $this->GetJiJieTime($dayType,$dayTime);
		$StartTime = $result['StartTime'];
		$EndTime = $result['EndTime'];
		//获取上班和下班时间

		$newlist = array();
		$list = parent::ShowAttend_effectual_LunBan(1,$EmpId = "");
		/* echo count($list);
		echo "<pre>";
		print_r($list);
		die(); */
		if(count($list) > 0) {
			foreach ($list as $key => $val) {
				if(strtotime($val['other']['riqi']) < $StartTime || strtotime($val['other']['riqi']) > $EndTime) continue;
				$newlist[$val['info']['emp_number']]['WorkHours'] += round($val['other']['WorkHours'],1);
				$newlist[$val['info']['emp_number']]['NeedWorkHours'] += round($val['other']['Hours'],1);
				if(isset($val['other']['later']) && $val['other']['later'] == 1) {
					$newlist[$val['info']['emp_number']]['later'] += 1;
					$newlist[$val['info']['emp_number']]['yeban'] += $val['other']['yeban'];
				} elseif(isset($val['other']['ZaoTui']) && $val['other']['ZaoTui'] == 1) {
					$newlist[$val['info']['emp_number']]['ZaoTui'] += 1;
				} elseif((isset($val['other']['LkuangGong']) && $val['other']['LkuangGong'] == 1) || (isset($val['other']['ZkuangGong']) && $val['other']['ZkuangGong'] == 1)) {
					$newlist[$val['info']['emp_number']]['kuangGong'] += 1;
				} else {
					$newlist[$val['info']['emp_number']]['yeban'] += $val['other']['yeban'];
				}
			}
		}
		
		return $newlist;
	}
	
	
	/**
	 *统计员工加班
	 **/
	public function StatisticsWorkOut($dayType=0,$dayTime="") {
		//获取开始和结束时间
		$result = $this->GetJiJieTime($dayType,$dayTime);
		$StartTime = $result['StartTime'];
		$EndTime = $result['EndTime'];
		//获取上班和下班时间

		$newlist = array();
		$newlist = parent::GetOutWordTIme($StartTime,$EndTime,2,$EmpId="");
		return $newlist;
	}
}
?>
